package com.streaminggbs.controller;

import com.streaminggbs.common.base.ErrorCodeException;
import com.streaminggbs.common.base.ReturnBean;
import com.streaminggbs.common.config.StaticConfig;
import com.streaminggbs.entity.LoginUser;
import com.streaminggbs.entity.NodeDept;
import com.streaminggbs.entity.SysAuthDept;
import com.streaminggbs.interfaces.SysAuthDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lilin
 * @date 2020-09-13 13:36
 * @discription 机构管理
 */
@Api(tags = {"机构管理接口"})
@Slf4j
@RestController
@RequestMapping("dept")
public class DeptController {

    @Autowired
    private SysAuthDeptService sysAuthDeptService;

    @ApiOperation(value = "获取子机构列表", notes = "获取子机构列表")
    @RequestMapping(value = "/getChildDeptList", method = RequestMethod.GET)
    public ReturnBean details(
            @ApiParam(value = "父机构ID") @RequestParam(value = "parentid", required = true) String parentid,
            @ModelAttribute LoginUser loginUser
    ) {
        log.info("======获取子机构列表======>parentid:" + parentid);
        try {
            List<SysAuthDept> childDeptList = sysAuthDeptService.getChildListByParentid(parentid);
            try {
                SysAuthDept sessionSysAuthDept = sysAuthDeptService.selectByKey(loginUser.getSysUser().getDeptid());
                String userDeptidnew = sessionSysAuthDept.getDeptidnew();
                List<SysAuthDept> childDeptListNew = new ArrayList<>();
                for (SysAuthDept sysAuthDept : childDeptList) {
                    String listDeptidnew = sysAuthDept.getDeptidnew();
                    if (listDeptidnew.contains(userDeptidnew) || userDeptidnew.contains(listDeptidnew)) {
                        childDeptListNew.add(sysAuthDept);
                    }
                }
                return new ReturnBean(childDeptListNew);
            }catch (Exception e){
                return new ReturnBean(childDeptList);
            }
        } catch (Exception e) {
            log.error("==机构管理==获取子机构列表报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "添加机构", notes = "添加机构")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ReturnBean add(
            @ApiParam(value = "父机构ID") @RequestParam(value = "parentid", required = true) String parentid,
            @ApiParam(value = "机构名称") @RequestParam(value = "deptname", required = true) String deptname,
            @ApiParam(value = "机构编码") @RequestParam(value = "gbId", required = true) String gbId,
            @ApiParam(value = "联系人") @RequestParam(value = "contract", required = false) String contract,
            @ApiParam(value = "电话") @RequestParam(value = "tel", required = false) String tel,
            @ApiParam(value = "地址") @RequestParam(value = "address", required = false) String address,
            @ApiParam(value = "机构类别（0部门 1单位 2其他）") @RequestParam(value = "depClass", required = false) Integer depClass,
            SysAuthDept entity
    ) {
        log.info("======添加机构======>parentid:" + parentid + "，deptname:" + deptname + "，gbId:" + gbId
                + "，contract:" + contract + "，tel:" + tel + "，address:" + address + "，depClass:" + depClass);
        try {
            String deptIdNew = sysAuthDeptService.getDeptIdNew(entity.getParentid());
            entity.setDeptidnew(deptIdNew);
            int count = sysAuthDeptService.addDept(entity);
            if (count == -1) {
                return new ReturnBean(-1, "机构编码已存在");
            }

            return new ReturnBean("保存成功");
        } catch (Exception e) {
            log.error("==机构管理==添加机构报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "编辑机构", notes = "编辑机构")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public ReturnBean edit(
            @ApiParam(value = "机构ID") @RequestParam(value = "deptid", required = true) String deptid,
            @ApiParam(value = "父机构ID") @RequestParam(value = "parentid", required = true) String parentid,
            @ApiParam(value = "机构名称") @RequestParam(value = "deptname", required = true) String deptname,
            @ApiParam(value = "机构编码") @RequestParam(value = "gbId", required = false) String gbId,
            @ApiParam(value = "联系人") @RequestParam(value = "contract", required = false) String contract,
            @ApiParam(value = "电话") @RequestParam(value = "tel", required = false) String tel,
            @ApiParam(value = "地址") @RequestParam(value = "address", required = false) String address,
            @ApiParam(value = "机构类别（0部门 1单位 2其他）") @RequestParam(value = "depClass", required = false) Integer depClass,
            SysAuthDept entity
    ) {
        log.info("======编辑机构======>deptid:" + deptid + "，parentid:" + parentid + "，deptname:" + deptname + "，gbId:" + gbId
                + "，contract:" + contract + "，tel:" + tel + "，address:" + address + "，depClass:" + depClass);
        try {

            int count = sysAuthDeptService.editDept(entity);
            if (count == -1) {
                return new ReturnBean(-1, "机构编码已存在");
            }

            return new ReturnBean("保存成功");
        } catch (Exception e) {
            log.error("==机构管理==编辑机构报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "删除机构", notes = "删除机构")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ReturnBean delete(
			@ModelAttribute LoginUser loginUser,
            @ApiParam(value = "机构ID") @RequestParam(value = "deptid", required = true) String deptid
    ) {
        log.info("======删除机构======>deptid:" + deptid);
        try {
            sysAuthDeptService.deleteDept(loginUser.getSysUser().getDeptid(),deptid);

            return new ReturnBean("保存成功");
        } catch (Exception e) {
            log.error("==机构管理==删除机构报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "获取下拉选择机构列表", notes = "获取下拉选择机构列表")
    @RequestMapping(value = "/getSelectTreeDeptList", method = RequestMethod.GET)
    public ReturnBean getSelectTreeDeptList(
            @ModelAttribute LoginUser loginUser
    ) {
        try {
            String deptid = loginUser.getSysUser().getDeptid();
            List<SysAuthDept> treeDeptList = sysAuthDeptService.getSelectTreeDeptList(deptid);
            if (treeDeptList == null || treeDeptList.isEmpty()) {
                log.info("获取下拉选择机构列表--未查询到机构，deptid=" + deptid);
                throw new ErrorCodeException(-1, "未查询到机构");
            }

            NodeDept node = new NodeDept();
            node.setParentid(treeDeptList.get(0).getParentid());
            node.setDeptid(treeDeptList.get(0).getDeptid());
            node.setDeptname(treeDeptList.get(0).getDeptname());

            doTree(node, treeDeptList);

            return new ReturnBean(node);
        } catch (Exception e) {
            log.error("==机构管理==获取下拉选择机构列表报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    /**
     * 拼接Node数据
     *
     * @param node
     * @param treeDeptList
     */
    public void doTree(NodeDept node, List<SysAuthDept> treeDeptList) {
        List<SysAuthDept> tempList = new ArrayList<>();
        for (SysAuthDept info : treeDeptList) {
            if (info.getDeptid().equals(node.getDeptid())) {
                continue;
            }
            if (info.getParentid().equals(node.getDeptid())) {
                NodeDept childrenNode = new NodeDept();
                childrenNode.setParentid(info.getParentid());
                childrenNode.setDeptid(info.getDeptid());
                childrenNode.setDeptname(info.getDeptname());
                node.getChildren().add(childrenNode);
            } else {
                tempList.add(info);
            }
        }

        if (!node.getChildren().isEmpty()) {
            List<NodeDept> childrenNodeList = node.getChildren();
            for (NodeDept childNode : childrenNodeList) {
                doTree(childNode, tempList);
            }
        }
    }
}
